﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TSOL.FastSPWeb.ValueObjects;

namespace TSOL.FastSPWeb.Core
{
    class FastSPWebGarbageCollectorThread
    {
        static Thread GarbageCollectorThread;

        public static void Start() {
            (GarbageCollectorThread = new Thread(GarbageCollectorTask)).Start();
        }
        public static void Stop()
        {
            GarbageCollectorThread.Abort();
        }
        static void GarbageCollectorTask()
        {
            while ((Thread.CurrentThread.ThreadState != ThreadState.AbortRequested) && (Thread.CurrentThread.ThreadState != ThreadState.StopRequested) && (Thread.CurrentThread.ThreadState != ThreadState.SuspendRequested))
            {
                Thread.Sleep(3 * 60 * 1000); // 3 min. 
                lock (FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.WebsCacheDictionary)
                {
                    DateTime invalidateTime = DateTime.Now.Subtract(new TimeSpan(0, 2, 55));
                    foreach (SPWebCacheCollection _SPCacheCollection in FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.WebsCacheDictionary.Values)
                    {
                        var ÍnvalidatedItems = _SPCacheCollection.Where(a => a.LastUsed < invalidateTime && a.Free == true).Select(n => n);
                        if (ÍnvalidatedItems.Any())
                        {
                            List<SPWebCacheEntity> removedKeys = new List<SPWebCacheEntity>();
                            foreach (SPWebCacheEntity _cache in ÍnvalidatedItems)
                            {
                                try
                                {
                                    _cache.Web.Dispose();
                                    _cache.Site.Dispose();
                                    _cache.Web = null;
                                    _cache.Site = null;
                                }
                                catch (Exception)
                                {
                                    // do Log...
                                }
                                finally
                                {
                                    removedKeys.Add(_cache);
                                }
                            }
                            foreach (SPWebCacheEntity key in removedKeys)
                                _SPCacheCollection.Remove(key);
                        }
                    }
                }
            }
        }

    }
}
